package map.android.baidu.carpool.page.pay;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.android.lbspay.view.ChannelListView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.api.ComAPIManager;
import com.baidu.mapframework.api.GetPayChannelListViewCallback;
import com.baidu.mapframework.api.PayCallback;
import com.baidu.mapframework.api.PayOrderByChannelListCallback;
import com.baidu.mapframework.app.fpstack.TaskManagerFactory;
import com.baidu.mapframework.widget.MProgressDialog;
import com.baidu.mapframework.widget.MToast;
import map.android.baidu.carpool.Config;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.GetPayData;
import map.android.baidu.carpool.model.DiscountItem;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.home.OrderDetailPage;
import map.android.baidu.carpool.page.usercenter.DiscountListPage;
import map.android.baidu.carpool.page.usercenter.OrderListPage;
import map.android.baidu.carpool.response.GetPayResponse;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.utils.NumberUtil;
import map.android.baidu.carpool.utils.StatisticsUtil;
import map.android.baidu.carpool.utils.TitleHelpler;

/**
 * Created by zhangtongyu on 15/4/1.
 * 支付收银台页面
 */
public class OrderPayPage extends CarpoolBasePage implements View.OnClickListener{
    private static String TAG = "PayPage";

    private Context mContext;
    private Resources mRes;
    private LayoutInflater mInflater;

    private View mView;
    private TitleHelpler mTitleHelper;

    private ChannelListView mPayLv;

    private TextView mOrderCostTv;
    private TextView mDiscountArrowTv;
    private TextView mShouldPayAmountTv;

    private LinearLayout mPayListContainerLin;
    private LinearLayout mConfirmPayContainerLin;
    private LinearLayout mDiscountArrowKLin;
    private Button mConfirmPayBt;

    private Bundle mBundle = new Bundle();

    private IDataStatusChangedListener<GetPayResponse> listener = new IDataStatusChangedListener<GetPayResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<GetPayResponse> data, GetPayResponse response, int dataStatus) {
            if (response != null && dataStatus == ComNetData.DATA_STATUS_SUCCESS && response.data != null) {

                    initPayWayList(response);

                    mOrderCostTv.setText(NumberUtil.subZeroAndDot(response.getFenAmount(response.data.payParam.originalAmount)) + "元");
                    if(response.data.hongbao != null) {
                        mDiscountArrowTv.setText(response.data.hongbao.hongbaoName);
                    }
                    mShouldPayAmountTv.setText("￥" + NumberUtil.subZeroAndDot(response.getFenAmount(response.data.payParam.payAmount)) + "元");
            } else {
                MToast.show((FragmentActivity)mContext, "网络连接异常，请检查网络");
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE, "");
        mContext = getActivity();
        mRes = APIProxy.res().getResources();
        mInflater = APIProxy.res().getInflater();

        if (mView == null) {
            mView = APIProxy.res().inflate(R.layout.layout_page_pay_cashier_desk);
            initView();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }

        GetPayData getPayData = new GetPayData(mContext);
        getPayData.setSdk("1");
        if (isNavigateBack()) {
            mBundle = getBackwardArguments();
            // 拿到bundle里面的红包id 发起请求
            if(mBundle.containsKey("orderId")){
                getPayData.setOrderId(mBundle.getString("orderId"));
            }
            if(mBundle.containsKey("removeDiscount")){
                mDiscountArrowTv.setText("请选择优惠券");
            } else {
                if (mBundle.containsKey("discount")) {
                    DiscountItem item = (DiscountItem) mBundle.getSerializable("discount");
                    if (item != null) {
                        getPayData.setdiscountId(item.discountId);
                        mDiscountArrowTv.setText(item.name);
                    }
                }
            }
            getPayData.post(listener);
        } else {
            // 拿到订单id 发起pay请求
            mBundle = getArguments();
            mDiscountArrowTv.setText("请选择优惠券");
            if(mBundle.containsKey("orderId")){
                getPayData.setOrderId(mBundle.getString("orderId"));
            }
            getPayData.post(listener);
        }
//        mBuilder = new CarpoolAlertDialog.Builder(getActivity());
        return mView;
    }

    private void initView() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBundle.putBoolean("needRefresh", true);
                goBack(mBundle);
            }
        });
        mTitleHelper.setCenterView("支付收银台");
        mDiscountArrowKLin = (LinearLayout) mView.findViewById(R.id.lin_discount_arrow);
        mOrderCostTv = (TextView) mView.findViewById(R.id.tv_order_cost);
        mDiscountArrowTv = (TextView) mView.findViewById(R.id.tv_discount_arrow);
        mShouldPayAmountTv = (TextView) mView.findViewById(R.id.tv_should_pay);
        mConfirmPayContainerLin = (LinearLayout) mView.findViewById(R.id.lin_confim_pay_container);
        mConfirmPayBt = (Button) mView.findViewById(R.id.bt_confim_pay);
        mPayListContainerLin = (LinearLayout) mView.findViewById(R.id.lin_container_pay_list);
        mConfirmPayBt.setOnClickListener(this);
        mDiscountArrowKLin.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();

        switch (viewId){
            case R.id.lin_discount_arrow:
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE, StatisticsUtil.OFFLINE_ACT_DISCOUNT_BT);
                mBundle.putString("from", this.getClass().getName());
                if(mBundle != null){
                    showLoadingDialog(true);
                    APIProxy.navi().navigateTo(DiscountListPage.class, mBundle);
                }
                break;
            case R.id.bt_confim_pay:
                mConfirmPayBt.setClickable(false);
                if(Config.MONKEY_OPEN){
                    return;
                }
                showLoadingDialog(true);
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE, StatisticsUtil.OFFLINE_ACT_PAY_BT);
                doPayAndHandleCallBack();
                break;
        }
    }
//    CarpoolAlertDialog.Builder mBuilder;
//    private void alertBackDialog(){
//        mBuilder.setNegativeButton("继续支付", new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //直接结束dialog
//            }
//        });
//        mBuilder.setPositiveButton("取消支付", new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mBundle.putBoolean("needRefresh", false);
//                goBack(mBundle);
//            }
//        });
//        mBuilder.setTitle("返回将取消支付");
//        mBuilder.create().show();
//    }


    private void initPayWayList(GetPayResponse response) {
		 /*
		  *  1， 创建支付自定义view
		  *  2， 回调处理button的enable状态
		  *  3， 支付
		  *  4， 支付成功处理loading dialog
		  */
        mPayLv = new ChannelListView(APIProxy.res().getBaseActivity());
        mPayListContainerLin.removeAllViews();
        mPayListContainerLin.addView(mPayLv);
        ComAPIManager.getComAPIManager().getPayAPI().getPayChannelListView(response.createDataHashMap(response.data), mPayLv,  new GetPayChannelListViewCallback() {

            @Override
            public void onFailed() {
                mConfirmPayContainerLin.setVisibility(View.GONE);
            }

            @Override
            public void onSuccess() {
                mConfirmPayContainerLin.setVisibility(View.VISIBLE);
                mConfirmPayBt.setClickable(true);
            }
        });
        MProgressDialog.dismiss();
    }

    //支付接口的回调处理
    PayCallback imPayCallBack = new PayCallback() {

        @Override
        public void onPayStatusChanged(int arg0, Bundle arg1) {
            LogUtils.d(TAG, "onPayStatusChanged() arg0 = " + arg0);
            switch (arg0) {
                case STATE_CODE_SUCCEED:
                    if(mBundle.containsKey("from") && OrderListPage.class.getName().equals(mBundle.getString("from"))){
                        TaskManagerFactory.getTaskManager().pop();
                        APIProxy.navi().navigateTo(OrderDetailPage.class, mBundle);
                    } else {
                        mBundle.putBoolean("needRefresh", true);
                        goBack(mBundle);
                    }
                    break;
                case STATE_CODE_PAYING:
                    MToast.show(mContext, "正在支付中");
                    break;
                case STATE_CODE_CANCEL:
                    MToast.show(mContext, "支付已取消");
                    break;
                case STATE_CODE_FAILED:
                    break;
                default:
                    break;
            }
        }
    };
    //发起支付并处理回调
    private void doPayAndHandleCallBack() {

        ComAPIManager.getComAPIManager().getPayAPI().requestPay(new PayOrderByChannelListCallback() {

            @Override
            public void onComplete() {
                showLoadingDialog(false);
                mConfirmPayBt.setClickable(true);
            }

        }, imPayCallBack);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        Bundle bundleForPayResult = data.getExtras();
        ComAPIManager.getComAPIManager().getPayAPI().getPayResult(bundleForPayResult);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public boolean onBackPressed() {
        mBundle.putBoolean("needRefresh", true);
        goBack(mBundle);
        return true;
    }

//    @Override
//    public void onDestroy() {
//        mBuilder = null;
//        super.onDestroy();
//    }
//
//    @Override
//    public void onDestroyView() {
//        mBuilder = null;
//        super.onDestroyView();
//    }
}
